/**
 * 获取小程序的H5链接
 */
import { Ref, ref } from "vue";
import ApiUser from "@/api/user";
import useFetch from "./useFetch";
import setting from "@/utils/setting";

interface Params {
  /**
   * 页面路径
   */
  path: string;
  /**
   * 参数
   * foo=bar&baz=qux
   * 默认：空
   */
  query?: string;
  /**
   * 开发、体验版、生成
   * 默认：生产
   */
  env_version?: "develop" | "trial" | "release";
}

interface Options {
  /**
   * 强制重新获取
   */
  force?: boolean;
}

const catchMap: Record<string, string> = {};

function useGetUrlLink(params: Params, { force }: Options = {}) {
  const catchUrl = ref<string>(catchMap[params.path] || "");

  const { data, refresh } = useFetch<{
    url_link: string;
  }>(
    ApiUser.generateMiniUrlLink,
    {
      immediate: force || !catchUrl.value,
      defaultParams: {
        env_version: setting.envVersion,
        ...params,
      },
      onSuccess() {
        catchUrl.value = catchMap[params.path] = data.value.url_link;
      },
    },
    { hiddenToast: true }
  );

  const events = { refresh };
  return [catchUrl, events] as [Ref<string>, typeof events];
}

export default useGetUrlLink;
